﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.UI;

public class LevelSecond : MonoBehaviour {
    public WaypointAnimation cameraWaypointAnimation;
    public CameraAnimation cameraAnimation;
    public DoorAnimation doorAnimation;
    public GameObject lediRoot;
    public Transform positionRoot;
    public Transform canvasSelect;
    public Transform condimentRoot;
    public Transform canvasCooking;
    public PlateController plateController;
    public GameObject hand;

    float _shakeInterval = 3f;
    Transform _transform;

    public int FoodMaterialCount {
        get; set;
    }

    public static LevelSecond Instance {
        get; private set;
    }

    void Awake() {
        if (Instance == null) {
            Instance = this;
        }
    }

    void Start() {
        _transform = transform;
        InvokeRepeating("DoorShake", 0f, _shakeInterval);
    }

    void DoorShake() {
        doorAnimation.Shake(ChineseRestaurantResPath.SFX_SHAKE_ICEBOX);
    }

    public void ShowHandTips(bool forceHide = false) {
        if (hand == null) {
            return;
        }

        if (SlicedTarget.Targets.Count == 1 && forceHide == false) {
            hand.SetActive(true);
        } else {
            hand.SetActive(false);
        }
    }

    bool _canClickLeDi = true;
    public void OnClickLeDi() {
        if (_canClickLeDi) {
            _canClickLeDi = false;
            var lediAnimation = lediRoot.GetComponentInChildren<LeDiAnimation>();

            if (lediAnimation) {
                lediAnimation.Talk(ChineseRestaurantResPath.LEDI_404040205, () => {
                    lediAnimation.Idle();
                    _canClickLeDi = true;
                });
            }
        }
    }

    bool _doorOpening;

    public void ClickDoor() {
        if (_doorOpening) {
            return;
        }

        _doorOpening = true;

        CancelInvoke();       
        doorAnimation.Idle();
        SpawnFoodMaterial();

        cameraAnimation.Forward().OnFinished(() => {
            cameraAnimation.animator.enabled = false;
            doorAnimation.Open(ChineseRestaurantResPath.SFX_DOOR_ICEBOX).OnFinished(() => {
                doorAnimation.GetComponent<BoxCollider>().enabled = false;
                ToStateSelect();
                _doorOpening = false;
            });
            Destroy(lediRoot);
        });
    }

    void SpawnFoodMaterial() {
        var names = GetFoodMaterials();
        var repeatCount = names.Count;

        for (var i = 0; i < repeatCount; i++) {
            var index = Random.Range(0, names.Count);
            var name = names[index];
            names.Remove(name);

            var path = ChineseRestaurantResPath.PREFAB_DIR + "Parent_" + name;
            var parent = positionRoot.GetChild(i);
            CommonUtility.InstantiateFrom(path, parent);
        }
    }

    int _showFoodMaterialCount = 6;

    List<string> GetFoodMaterials() {
        var foodNames = ChineseRestaurantManager.Instance.GetFoodMaterialFromCurrentDishName();
        var allNames = new List<string>(System.Enum.GetNames(typeof(FoodName)));
        var list = new List<string>();

        FoodMaterialCount = foodNames.Length;

        foreach (var name in foodNames) {
            allNames.Remove(name.ToString());
            list.Add(name.ToString());
        }
        
        var randomCount = _showFoodMaterialCount - list.Count;

        for (var i = 0; i < randomCount; i++) {
            var index = Random.Range(0, allNames.Count);
            var name = allNames[index];
            allNames.Remove(name);
            list.Add(name);
        }

        return list;
    }

    // 选食材
    void ToStateSelect() {       
        canvasSelect.SetActive(true);
        AudioManager.Instance.PlaySound(ChineseRestaurantResPath.VOICE_SELECT_STATE_ENTER);

        var foodNames = ChineseRestaurantManager.Instance.GetFoodMaterialFromCurrentDishName();
        var panel = canvasSelect.GetChild(0) as RectTransform;

        switch (foodNames.Length) {
            case 2:
                panel.sizeDelta = new Vector2(280f, 600f);
                break;
            case 1:
                panel.sizeDelta = new Vector2(280f, 400f);
                break;
        }

        for (var i = 0; i < panel.childCount; i++) {
            if (i >= foodNames.Length) {
                panel.GetChild(i).SetActive(false);
                continue;
            }

            var iamge = panel.GetChild(i).GetComponent<Image>();
            var spriteName = ChineseRestaurantManager.Instance.GetSpriteNameFrom(foodNames[i]);
            iamge.sprite = CommonUtility.GetChineseRestaurantSprite(spriteName + "_jy");
        }
    }

    // 切菜
    public void ToStateCut() {
        StartCoroutine(TimeUtility.DelayInvoke(1f, () => {
            var duration = AudioManager.Instance.PlaySound(ChineseRestaurantResPath.VOICE_SELECT_STATE_EXIT).Length;
            StartCoroutine(TimeUtility.DelayInvoke(duration, () => {
                Destroy(doorAnimation.GetComponent<UnityEngine.EventSystems.EventTrigger>());
                doorAnimation.GetComponent<BoxCollider>().enabled = true;
                doorAnimation.Close().OnFinished(() => {
                    cameraWaypointAnimation.transform.localPosition = cameraWaypointAnimation.waypoints[0].target.localPosition;
                    cameraWaypointAnimation.transform.localEulerAngles = cameraWaypointAnimation.waypoints[0].target.localEulerAngles;
                    CreateSlicer();
                });
            }));
        }));
    }

    // 炒菜
    public void ToStateCooking() {
        CancelInvoke();
        ShrimpController.Destroy();

        var t = CommonUtility.InstantiateFrom(ChineseRestaurantResPath.PAN, transform);
        t.GetComponentInChildren<Collider>().material = ChineseRestaurantManager.Instance.PhysicMat;

        var x = (ChineseRestaurantManager.Instance.GetFoodMaterialFromCurrentDishName().Length == 1) ? -0.3f : -0.7f;
        plateController.transform.localPosition = new Vector3(x, 0f, -0.1f);

        foreach (Transform plate in plateController.transform) {
            plate.gameObject.AddComponent<DragPlate>().height = 0.65f;
        }

        ChineseRestaurantManager.Instance.RestoreFriction();
        cameraWaypointAnimation.transform.localPosition = cameraWaypointAnimation.waypoints[1].target.localPosition;
        cameraWaypointAnimation.transform.localEulerAngles = cameraWaypointAnimation.waypoints[1].target.localEulerAngles;

        // 设置调料初始位置
        condimentRoot.localPosition = Vector3.right;

        PlayFiringTips();
    }

    // 煲汤
    public void ToStateSoup() {
        CancelInvoke();

        var t = CommonUtility.InstantiateFrom(ChineseRestaurantResPath.STOCKPOT, transform);
        t.GetComponentInChildren<Collider>().material = ChineseRestaurantManager.Instance.PhysicMat;

        plateController.transform.localPosition = new Vector3(4.35f, 0f, -2.65f);
        plateController.transform.localEulerAngles = Vector3.up * -90f;

        foreach (Transform plate in plateController.transform) {
            plate.gameObject.AddComponent<DragPlate>().height = 0.9f;
        }

        ChineseRestaurantManager.Instance.CancelFriction();
        cameraWaypointAnimation.transform.localPosition = cameraWaypointAnimation.waypoints[2].target.localPosition;
        cameraWaypointAnimation.transform.localEulerAngles = cameraWaypointAnimation.waypoints[2].target.localEulerAngles;

        // 设置调料初始位置
        condimentRoot.localPosition = new Vector3(1.25f, 0f, -2.95f);
        condimentRoot.localEulerAngles = Vector3.up * 90f;

        PlayFiringTips();
    }

    void PlayFiringTips() {
        var delay = 5f;
        StartCoroutine(TimeUtility.DelayInvoke(delay, () => {
            if (SwitchController.IsOn) {
                return;
            }

            var fc = FindObjectOfType<ForceController>();

            if (fc) {
                AudioManager.Instance.PlaySound(ChineseRestaurantResPath.LEDI_404040301);
            }
        }));
    }

    public void ShowConfirmButton() {
        if (canvasCooking.gameObject.activeInHierarchy == false) {
            canvasCooking.SetActive(true);
            AudioManager.Instance.PlaySound(ChineseRestaurantResPath.SFX_PUSH_CONDIMENT);
        }
    }

    public void ShowButtonVFX() {
        ShowConfirmButton();
        canvasCooking.GetChild(0).GetChild(0).SetActive(true);
    }

    public void ShowCondiment() {
        condimentRoot.SetActive(true);
        AudioManager.Instance.PlaySound(ChineseRestaurantResPath.SFX_PUSH_CONDIMENT);

        if (ChineseRestaurantManager.Instance.currentDishName == DishName.QingCaiDouFuTang) {
            condimentRoot.DOLocalMove(new Vector3(1.25f, 0f, -1.95f), 0.5f).OnComplete(EnableCondimentBehaviour);
        } else {
            condimentRoot.DOLocalMove(Vector3.zero, 0.5f).OnComplete(EnableCondimentBehaviour);
        }

        if (SwitchController.IsOn == false) {
            PlayFiringTips();
        }

        StartCoroutine(TimeUtility.DelayInvoke(15f, ShowConfirmButton));
    }

    void EnableCondimentBehaviour() {
        var dcs = condimentRoot.GetComponentsInChildren<DragCondiment>(true);

        foreach (var dc in dcs) {
            dc.enabled = true;
        } 
    }

    void CreateSlicer() {
        TargetSlicer.Instance.camera = cameraAnimation.GetComponent<Camera>();
        TargetSlicer.Instance.enabled = false;

        var foodCount = ChineseRestaurantManager.Instance.GetFoodMaterialFromCurrentDishName().Length;

        if (ChineseRestaurantManager.Instance.currentDishName == DishName.QingChaoXiaRen) {
            foodCount = 1;
        }

        var sliceCount = 0;
        TargetSlicer.Instance.onSliceComplete += () => {
            sliceCount += 1;

            if (sliceCount >= foodCount) {
                Transform switchParent;

                if (ChineseRestaurantManager.Instance.currentDishName.Equals(DishName.QingCaiDouFuTang)) {
                    var duration = AudioManager.Instance.PlaySound(ChineseRestaurantResPath.VOICE_CUT_STATE_EXIT_SOUP).Length;
                    StartCoroutine(TimeUtility.DelayInvoke(duration, ToStateSoup));
                    switchParent = _transform.Find("Stockpot Switch");
                } else {
                    var duration = AudioManager.Instance.PlaySound(ChineseRestaurantResPath.VOICE_CUT_STATE_EXIT_COOKING).Length;
                    StartCoroutine(TimeUtility.DelayInvoke(duration, ToStateCooking));
                    switchParent = _transform.Find("Pan Switch");
                }

                switchParent.gameObject.AddComponent<SwitchController>();
                TargetSlicer.DestroyInstance();
                Destroy(TurboSlice.instance.gameObject);

                var switchEffect = CommonUtility.InstantiateFrom(ChineseRestaurantResPath.VFX_SWITCH_TIPS, switchParent);

                if (ChineseRestaurantManager.Instance.currentDishName == DishName.QingCaiDouFuTang) {

                } else {
                    switchEffect.localPosition += Vector3.up * -0.02f;
                }
            }
        };

        plateController.SpawnPlateAndFood();
        Destroy(canvasSelect.gameObject);
        Destroy(positionRoot.gameObject);
        Destroy(doorAnimation.transform.parent.gameObject);

        InvokeRepeating("RandomShake", 0f, _randomShakeInterval);
    }

    float _randomShakeInterval = 5f;
    void RandomShake() {
        if (SlicedTarget.Targets.Count > 0 || DragAndClickTrigger.IsDraging || DragAndClickTrigger.IsMoving) {
            return;
        }

        var dcts = FindObjectsOfType<DragAndClickTrigger>();

        if (dcts != null && dcts.Length > 0) {
            var dct = dcts[Random.Range(0, dcts.Length)];
            dct.gameObject.AddComponent<ShakeFX>();
        }
    }

    public void ToNextLevel() {
        AudioManager.Instance.PlaySound(ChineseRestaurantResPath.SFX_BUTTON_CONFIRM);

        if (SwitchController.IsOn) {
            var sc = FindObjectOfType<SwitchController>();

            if (sc != null) {
                sc.OnPointerClick(null);
            }
        }

        AudioManager.Instance.PlaySound(ChineseRestaurantResPath.SFX_SUCCESS);

        var voicePath = "";
        switch (ChineseRestaurantManager.Instance.currentDishName) {
            case DishName.DongPoRou:
                voicePath = ChineseRestaurantResPath.DISH_NAME_DPR_FINISH;
                break;
            case DishName.HongShaoYu:
                voicePath = ChineseRestaurantResPath.DISH_NAME_HSY_FINISH;
                break;
            case DishName.HuangGuaHuoTui:
                voicePath = ChineseRestaurantResPath.DISH_NAME_HGHT_FINISH;
                break;
            case DishName.QingCaiDouFuTang:
                voicePath = ChineseRestaurantResPath.DISH_NAME_QCDFT_FINISH;
                break;
            case DishName.QingChaoXiaRen:
                voicePath = ChineseRestaurantResPath.DISH_NAME_QCXR_FINISH;
                break;
            case DishName.QingJiaoPeiGen:
                voicePath = ChineseRestaurantResPath.DISH_NAME_QJPG_FINISH;
                break;
        }
        AudioManager.Instance.PlaySound(voicePath);

        var height = (ChineseRestaurantManager.Instance.currentDishName == DishName.QingCaiDouFuTang) ? 0.4f : 0.2f;
        var pos = FindObjectOfType<ForceController>().transform.position + (Vector3.up * height);
        var vfx = CommonUtility.InstantiateFrom(ChineseRestaurantResPath.VFX_SUCCESS, null);
        vfx.position = pos;
        vfx.gameObject.AddComponent<ParticleSystemFate>();

        StartCoroutine(TimeUtility.DelayInvoke(2f, () => ChineseRestaurantManager.Instance.ToNextLevel()));
    }
}
